package com.ytjj.qmyx.mall.utils;

import com.ytjj.qmyx.mall.builder.MyBoolQueryBuilder;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;


/**
 *
 * @version 1.0
 *
 */
public class EsUtils {

    public static final Integer MIN_SCORE = 6;

    public static final Integer MIN_SCORE_1 = 1;

    public static SearchQuery createSearchQuery(BoolQueryBuilder boolQueryBuilder, Integer minScore, String... index) {
        MyBoolQueryBuilder myBoolQueryBuilder = (MyBoolQueryBuilder) boolQueryBuilder;
        Pageable pageable = PageRequest.of(myBoolQueryBuilder.getPageNum(), myBoolQueryBuilder.getPageSize());
        return new NativeSearchQueryBuilder()
                .withQuery(myBoolQueryBuilder)
                .withTypes("doc")
                .withIndices(index)
                .withMinScore(minScore)
                .withPageable(pageable)
                .build();
    }

    public static SearchQuery createSortSearchQuery(BoolQueryBuilder boolQueryBuilder,Integer minScore, String sortName,SortOrder sortOrder, String... index) {
        MyBoolQueryBuilder myBoolQueryBuilder = (MyBoolQueryBuilder) boolQueryBuilder;
        Pageable pageable = PageRequest.of(myBoolQueryBuilder.getPageNum(), myBoolQueryBuilder.getPageSize());
        return new NativeSearchQueryBuilder()
                .withQuery(myBoolQueryBuilder)
                .withTypes("doc")
                .withIndices(index)
                .withMinScore(minScore)
                .withPageable(pageable)
                .withSort(SortBuilders.fieldSort(sortName).order(sortOrder))
                .build();
    }

    public static SearchQuery createSortSearchQuery(BoolQueryBuilder boolQueryBuilder,String sortName,SortOrder sortOrder, String... index) {
        MyBoolQueryBuilder myBoolQueryBuilder = (MyBoolQueryBuilder) boolQueryBuilder;
        Pageable pageable = PageRequest.of(myBoolQueryBuilder.getPageNum(), myBoolQueryBuilder.getPageSize());
        return new NativeSearchQueryBuilder()
                .withQuery(myBoolQueryBuilder)
                .withTypes("doc")
                .withIndices(index)
//                .withMinScore(minScore)
                .withPageable(pageable)
                .withSort(SortBuilders.fieldSort(sortName).order(sortOrder))
                .build();
    }
}
